<template>
    <div class="container">
        <el-card>
            <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
                <div class="payAttention">*首页共6个快捷通道入口，强制显示2个，用户可自定义4个</div>
                <div class="between">
                    <div class="between">
                        <div class="menu-item">菜单列表</div>
                        <el-input
                            class="input"
                            placeholder="输入关键字进行过滤"
                            v-model="filterText"
                        ></el-input>
                    </div>
                    <div>
                        <el-button
                            type="success"
                            size="mini"
                            style="margin-right: 24px"
                            @click="handleSubmit"
                        >
                            保存
                        </el-button>
                        <span class="text">用户自定义</span>
                        <span class="text">强制显示</span>
                    </div>
                </div>
                <template v-for="item in paneList">
                    <el-tab-pane :label="item.label" :name="item.name" :key="item.name">
                        <el-tree
                            :data="menus"
                            node-key="authId"
                            :props="defaultProps"
                            :highlight-current="true"
                            @node-click="nodeClick"
                            :filter-node-method="filterNode"
                            ref="tree"
                            :default-expanded-keys="defaultExpandedKeys"
                            v-if="item.name == activeName"
                        >
                            <span slot-scope="{ node, data }" class="custom-tree-node">
                                <span :title="node.label">{{ getLabelStr(node.label) }}</span>
                                <span v-if="!data.children">
                                    <el-checkbox
                                        :true-label="2"
                                        :false-label="0"
                                        v-model="data.forcedDisplay"
                                        
                                        @change="(newVal) => boxChange(newVal, data)"
                                    ></el-checkbox>
                                    <el-checkbox
                                        :true-label="1"
                                        :false-label="0"
                                        v-model="data.forcedDisplay"
                                        @change="(newVal) => boxChange(newVal, data)"
                                    ></el-checkbox>
                                </span>
                            </span>
                        </el-tree>
                    </el-tab-pane>
                </template>
            </el-tabs>
        </el-card>
    </div>
</template>

<script>
import { getAuthorities, updateAuthorityMenuList } from 'common/src/api/user'
export default {
    name: 'ShortcutConfigutation',
    data() {
        return {
            activeName: '',
            menus: [],
            paneList: [
                { label: '管理员菜单', name: 1 },
                {
                    label: '教师菜单',
                    name: 2,
                },
                {
                    label: '学生菜单',
                    name: 3,
                },
            ],
            defaultProps: {
                children: 'children',
                label: 'label',
            },
            checkedList: [], //选中的菜单listMap格式
            defaultExpandedKeys: [], //默认展开的菜单
            filterText: '',
        }
    },
    mounted() {
        //默认处理管理员菜单相关
        this.activeName = 1
        this.queryMenuList(1)
    },
    watch: {
        filterText(val) {
            this.$refs.tree.length > 0 && this.$refs.tree[0].filter(val)
        },
    },
    methods: {
        filterNode(value, data) {
            if (!value) return true
            return data.label.indexOf(value) !== -1
        },
        handleClick() {
            this.queryMenuList(this.activeName)
        },
        async queryMenuList(roleType) {
            let { code, data } = await getAuthorities({ roleType: roleType })
            if (code !== 200) return
            data.forEach((item) => {
                item.label = item.authNameCh
                if (item.forcedDisplay || item.passageWay) {
                    this.defaultExpandedKeys.push(item.authId)
                }
            })
            this.menus = this.$utils.listToTree(
                'authId',
                'parentAuthId',
                data.filter((item) => item.type !== 2)
            )
        },
        getLabelStr(str) {
            if (!str) {
                return ''
            } else {
                return str.length > 10 ? str.substring(0, 10).concat('...') : str
            }
        },
        boxChange(status, option) {
            this.checkedList.push(option)
            this.checkedList = _.unionBy(this.checkedList, 'authId')
            // 调用接口更新菜单显示状态 需要优化
        },
        handleSubmit() {
            try {
                if (this.checkRange(this.menus, 6, 'forcedDisplay')) {
                    this.updateMenuList()
                }
            } catch (err) {
                this.$message({
                    type: 'warning',
                    message: '强制显示菜单不能超过6个',
                })
            }
        },
        async updateMenuList() {
            let list = this.checkedList
            //强制显示的菜单默认放进快捷通道中
            list.forEach((item) => {
                if (item.forcedDisplay == 1) {
                    item.passageWay = 1
                } else {
                    item.passageWay = 0
                }
            })
            let { code } = await updateAuthorityMenuList(list)
            if (code !== 200) return
            this.$message({
                type: 'success',
                message: '保存成功',
            })
            this.checkedList = [];
        },
        checkRange(array, num, keyWord) {
            let index = 0,
                status = true
            function cycle(array) {
                array.forEach((item) => {
                    if (item[keyWord] == 1) {
                        index++
                        if (index > num) {
                            status = status
                            throw 'The number of keywords is out of range'
                        }
                    }
                    if (item.children && item.children.length > 0) {
                        cycle(item.children)
                    }
                })
            }
            cycle(array)
            return status
        },
        // nodeClick(obj,node,el){
        //     console.log(obj,node,el)
        // },
        multiToOne(array = []) {
            if (array.length == 0) return []
            let result = []
            let index = 0
            function cycle(array) {
                array.map((cur, index) => {
                    cur[`itemName${index}`] = cur.authNameCh
                    result.push(cur)
                    if (cur.children && cur.children.length > 0) {
                        index++
                        cycle(cur.children)
                    }
                })
            }
            cycle(array)
            return result
        },
    },
}
</script>
<style lang="scss" scoped>
::v-deep {
    .el-main {
        overflow: hidden !important;
    }
}
.container {
    position: relative;
    .payAttention {
        text-align: end;
        color: red;
        position: fixed;
        top: 168px;
        right: 50px;
    }
    .text {
        margin-right: 8px;
    }

    .between {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
        align-items: center;
        .menu-item {
            padding-left: 24px;
            font-weight: bold;
            font-size: 18px;
        }
        .input {
            width: 160px;
            margin-left: 16px;
        }
    }
    ::v-deep {
        // .el-tabs__content {
        //     width: 65% !important;
        // }
        .el-checkbox {
            margin-right: 30px;
        }
        .el-tree {
            overflow: scroll;
            height: calc(68vh - 100px);
            overflow-x: hidden;
        }
        .el-checkbox__inner  {
            border:1px solid black
        }  
    }
    .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 4px;
        color: #3f3f3f;
        // width: 400px;
    }
}
</style>